/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package tk.mybatis.springboot.service.impl;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.umuw.core.util.MD5;

import net.sf.json.JSONObject;
import tk.mybatis.springboot.api.controller.BaseController;
import tk.mybatis.springboot.mapper.DianxinPlayerMapper;
import tk.mybatis.springboot.mapper.JforumPostsTextMapper;
import tk.mybatis.springboot.mapper.TAccountWeixinMapper;
import tk.mybatis.springboot.mapper.TUserprofileMapper;
import tk.mybatis.springboot.model.Jforum;
import tk.mybatis.springboot.model.Message;
import tk.mybatis.springboot.model.Subjsct;
import tk.mybatis.springboot.model.TAccountWeixin;
import tk.mybatis.springboot.model.TDianxinPlayer;
import tk.mybatis.springboot.model.TUserprofile;
import tk.mybatis.springboot.service.DianxinService;
import tk.mybatis.springboot.wexin.bean.Userinfo;
import tk.mybatis.springboot.wexin.util.RedisUtils;
import tk.mybatis.springboot.wexin.util.StringUtils;

@Service
@Transactional
public class DianxinServiceImpl implements DianxinService{

    @Autowired
    private DianxinPlayerMapper dianxinMapper;
    @Autowired
    private JforumPostsTextMapper jforumPostsTextMapper;
    
    @Autowired
    private TAccountWeixinMapper tAccountWeixinMapper;
    
    @Autowired
    private TUserprofileMapper tUserprofileMapper;
    
    private final static Pattern ATTR_PATTERN = Pattern.compile("<img[^<>]*?\\ssrc=['\"]?(.*?)['\"]?\\s.*?>",Pattern.CASE_INSENSITIVE);

	@Override
	public JSONObject getDianxin(String openid, String userName, String phoneNum, String idCard, String giftCard,
			String minuteAdd, String postCode) throws Exception {
		TDianxinPlayer dianxinPlayer = dianxinMapper.selectOpenid(openid);
		if(dianxinPlayer != null){
			return BaseController.error("您已经领取过电信福利了！", "0014");
		}
		dianxinPlayer = new TDianxinPlayer();
		dianxinPlayer.setGift_card(giftCard);
		dianxinPlayer.setId_card(idCard);
		dianxinPlayer.setMinute_add(minuteAdd);
		dianxinPlayer.setPhone_num(phoneNum);
		dianxinPlayer.setPost_code(postCode);
		dianxinPlayer.setUser_name(userName);
		dianxinPlayer.setOpen_id(openid);
		int result = dianxinMapper.insertSelective(dianxinPlayer);
		if(result == 0){
			return BaseController.error("领取失败！", "9999");
		}else{
			return BaseController.success("领取成功！");
		}
	}

	@Override
	public List<Subjsct> getSubjectList(String row, String page) {
		if(StringUtils.isEmpty(row)){
			row = "5";
		}
		if(StringUtils.isEmpty(page)){
			page = "1";
		}
		PageHelper.startPage(Integer.valueOf(page).intValue(), Integer.valueOf(row).intValue());
		List<Subjsct> subjectList = jforumPostsTextMapper.getSubjectList();
		for (Subjsct subjsct : subjectList) {
			Matcher matcher = ATTR_PATTERN.matcher(subjsct.getPostText().toString());
			String str="";
		    while (matcher.find()) {
			   str = matcher.group(1);
			 }
			System.out.println(str);
		    if(!str.equals("")){
			    System.out.println(str);
			    String cell[]= str.split("/>");
			    if(cell.length>0){
			    	subjsct.setImage(cell[0].toString());
			    } else{
			    	subjsct.setImage("http://ydche.com/media/mcimg/60a43006e780420eac0063e792a589c4.png");
			    }
		    }
		    subjsct.setPostText("");
		}
		return subjectList;
	}

	@Override
	public Jforum getSubjectText(String subjectID) {
		jforumPostsTextMapper.addViewCount(subjectID);
		Jforum subjectText = jforumPostsTextMapper.getSubjectText(subjectID);
		return subjectText;
	}

	@Override
	public Boolean getStatus(String openId) {
		TAccountWeixin tAccountWeixinByOpenId = tAccountWeixinMapper.getTAccountWeixinByOpenId(openId);
		return tAccountWeixinByOpenId != null;
	}

	@Override
	public String getMobile(String openId) {
		TAccountWeixin tAccountWeixinByOpenId = tAccountWeixinMapper.getTAccountWeixinByOpenId(openId);
		TUserprofile tUserprofile = tUserprofileMapper.selectByPrimaryKey(tAccountWeixinByOpenId.getUserprofileId());
		return tUserprofile.getMobile();
	}

	@Override
	public Message verifyCode(HttpServletRequest request, String mobile, String code) {
		String str = RedisUtils.getStr(mobile);
		if(!str.trim().equals(code)){
			return Message.error("验证码错误");
		}
		HttpSession session = request.getSession();
		Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
		String openid = userinfo.getOpenid();
		TUserprofile tUserprofile = new TUserprofile();
		tUserprofile.setMobile(mobile);
		List<TUserprofile> tUserprofiles = tUserprofileMapper.select(tUserprofile);
		if(tUserprofiles.size() != 0){
			TAccountWeixin tAccountWeixinByOpenId = tAccountWeixinMapper.getTAccountWeixinByUserid(tUserprofiles.get(0).getId());
			if(tAccountWeixinByOpenId != null ){
				return Message.error("该手机号已经绑定了其他微信");
			}
			tAccountWeixinByOpenId = new TAccountWeixin();
			tAccountWeixinByOpenId.setOpen_id(openid);
			tAccountWeixinByOpenId.setUserprofileId(tUserprofiles.get(0).getId());
			tAccountWeixinMapper.insertSelective(tAccountWeixinByOpenId);
			return Message.success();
		}
		tUserprofile.setUser_name(userinfo.getNickname());
		tUserprofile.setPwd("123456");
		tUserprofile.setType_id(1);
		tUserprofile.setRegister_time(new Date());
		tUserprofile.setIs_admin(1);
		tUserprofile.setIs_enabled(0);
		tUserprofile.setIs_locked(0);
		tUserprofileMapper.myInsert(tUserprofile);
		String pwd = MD5.UMencode(tUserprofile.getMobile(), String.valueOf(tUserprofile.getId()));
		tUserprofile.setPwd(pwd);
		tUserprofileMapper.updateByPrimaryKeySelective(tUserprofile);
		TAccountWeixin tAccountWeixinByOpenId = new TAccountWeixin();
		tAccountWeixinByOpenId.setOpen_id(openid);
		tAccountWeixinByOpenId.setUserprofileId(tUserprofile.getId());
		tAccountWeixinMapper.insertSelective(tAccountWeixinByOpenId);
		session.setAttribute("user_id", tUserprofile.getId());
		return Message.success();
	}

}
